<template>
    <a-drawer v-model:open="state.config.visible" @close="close()" v-bind="state.config">
        <template #title>
            {{ state.titleTxt }}
        </template>
        <div class="w-full h-full" v-if="!state.config.loading">
            <a-form class="flex flex-col h-full bbcc" ref="formRef" :model="formData" v-bind="state.form" @finish="onSubmit">
                <div class="h-full p-6 pb-20 overflow-y-auto">
                    <div class="grid grid-cols-2 gap-2">
                        <a-form-item label="任务状态" name="taskStatus" :rules="[{ required: false, message: '请填写' }]">
                            <d-select :disabled="state.modelType === 2 ? true : false" :search="true" v-model:value="formData.taskStatus" :options="taskStatus" />
                        </a-form-item>
                        <a-form-item label="任务类型" name="taskType" :rules="[{ required: true, message: '请填写' }]">
                            <d-select :disabled="true" :search="true" v-model:value="formData.taskType" :options="taskType" />
                        </a-form-item>
                        <a-form-item label="执行人" name="director" :rules="[{ required: true, message: '请填写' }]">
                            <d-org type="USER" :disabled="state.modelType === 2 ? true : false" v-model:value="formData.directorId" v-model:name="formData.director" @change="choose" />
                        </a-form-item>
                        <a-form-item label="负责人工号" name="directorNumber" :rules="[{ required: false, message: '请填写' }]" v-show="false">
                            <d-input :disabled="state.modelType === 2 ? true : false" v-model:value="formData.directorNumber" />
                        </a-form-item>
                        <a-form-item label="部门" name="department" :rules="[{ required: true, message: '请填写' }]" v-if="formData.directorId">
                            <d-input type="dept" :disabled="true" v-model:value="formData.department" placeholder="填写执行人后自动带出" />
                            <a-form-item-rest><d-input v-show="false" v-model:value="formData.departmentId" /> </a-form-item-rest>
                        </a-form-item>
                        <a-form-item label="客户名称" name="customerName" :rules="[{ required: true, message: '请选择' }]">
                            <d-select :allowClear="false" :disabled="state.modelType === 2 ? true : false" v-model:value="formData.customerName" :open="false" @click="chooseCustomerRef.openModel(0)" @change="getCustomerVal" />
                        </a-form-item>
                        <a-form-item label="截止时间" name="deadline" :rules="[{ required: true, message: '请填写' }]">
                            <d-time :disabled="state.modelType === 2 ? true : false" v-model:value="formData.deadline" :disabledDate="disabledEndDate" />
                        </a-form-item>
                        <a-form-item label="任务下发人" name="taskSender" :rules="[{ required: false, message: '请填写' }]">
                            <d-org type="USER" :disabled="state.modelType === 2 ? true : false" v-model:value="formData.taskSenderId" v-model:name="formData.taskSender" />
                        </a-form-item>
                        <a-form-item label="下发方式" name="sendType" :rules="[{ required: true, message: '请填写' }]">
                            <d-select :disabled="true" :search="true" v-model:value="formData.sendType" :options="sendType" />
                        </a-form-item>
                        <a-form-item label="任务下发时间" name="taskSendTime" :rules="[{ required: true, message: '请填写' }]">
                            <d-time :disabled="state.modelType === 2 ? true : false" v-model:value="formData.taskSendTime" />
                        </a-form-item>
                    </div>
                    <div class="grid grid-cols-1 gap-2">
                        <a-form-item label="任务要求" name="taskRequire" :rules="[{ required: true, message: '请填写' }]">
                            <d-textarea :rows="6" placeholder="提示:最多输入200字" :disabled="state.modelType === 2 ? true : false" v-model:value="formData.taskRequire" />
                        </a-form-item>
                    </div>
                </div>
            </a-form>
            <chooseCustomer ref="chooseCustomerRef" @change="getCustomerInfo" :customerInfo="state.customerInfo"></chooseCustomer>
        </div>
        <div v-else class="flex-center">
            <a-spin />
        </div>
        <template #footer>
            <div class="p-3" style="text-align: center" v-if="state.modelType !== 2">
                <a-space :size="10">
                    <a-button type="primary" @click="onSubmit" :loading="state.btnLoading">提交</a-button>
                    <a-button @click="close">取消</a-button>
                </a-space>
            </div>
        </template>
    </a-drawer>
</template>

<script setup>
import { taskStatus, sendType, taskType } from '../home'
import chooseCustomer from '../../global/chooseCustomer/choose.vue'
const emits = defineEmits(['save'])
const state = reactive({
    chooseCustomerRef: undefined,
    form: XEUtils.clone(formConfig, true), //表单配置
    config: XEUtils.clone(drawerConfig, true), //窗口配置
    formRef: null, //表单实例
    formData: {}, //表单数据
    modelType: 0, //0-新增 1-编辑 2-详情
    datas: {},
    store: useStore(),
    btnLoading: false,
    titleTxt: '新增',
    show: false,
})

//提交

const onSubmit = () => {
    state.formRef.validateFields().then(values => {
        state.btnLoading = true
        setTimeout(() => {
            state.btnLoading = false
        }, 1000)
        const deadline = dayjs(values.deadline).valueOf()
        const taskSendTime = dayjs(values.taskSendTime).valueOf()
        values.deadline = deadline
        values.taskSendTime = taskSendTime
        const visits = {
            directorId: state.formData.directorId,
            departmentId: state.formData.departmentId,
            taskSenderId: state.formData.taskSenderId,
            directorNumber: state.formData.directorNumber,
        }
        Object.assign(values, visits, { customerId: state.formData.customerId, uscc: state.formData.uscc })
        if (state.modelType === 0) {
            axios.postJson(`/api/zyrwSendDetail`, values).then(res => {
                emits('save')
            })
        }
        // else {

        // Object.assign(values, {id:state.formData.id})

        //     axios.put(`/api/zzfSendDetail`, values).then(res => {

        //         emits('save')

        //     })

        // }
        close()
    })
}

const choose = () => {
    if (state.formData.director) {
        axios
            .get('/api/dingtalkDeptExt/getByUserId', { userId: state.formData.directorId })
            .then(res => {
                state.formData.department = res.data[0].name
                state.formData.departmentId = res.data[0].id.toString()
                resolve(res)
            })
            .catch(err => {
                reject()
            })

        axios
            .postJson('/api/dingtalk/topapi/v2/user/get', { userid: state.formData.directorId })
            .then(res => {
                if (res.data.result.jobNumber === '') {
                    state.formData.directorNumber = ''
                } else {
                    state.formData.directorNumber = res.data.result.jobNumber
                }
                resolve(res)
            })
            .catch(err => {
                reject()
            })
    }
}

//清除已选客户

function getCustomerVal(val) {
    if (val === undefined) {
        state.customerInfo = []
    }
}

//获取已选客户

function getCustomerInfo(item) {
    state.formData.customerName = item[0].custName
    state.formData.customerId = item[0].custId
    state.formData.uscc = item[0].idTyyx
    state.customerInfo = item
}

//查看

async function viewFun(datas) {
    state.config.loading = false
    state.formData = XEUtils.clone(datas, true)
}

//创建

async function createFun() {
    state.titleTxt = '新增'
    state.config.loading = false
    // state.formData = {
    //     q: state.store.users.id,
    //     qName: state.store.users.name,
    //     s: state.store.users.id,
    //     sName: state.store.users.name,
    // }
    state.formData.sendType = '1'
    state.formData.taskType = '0'
    state.formData.taskSendTime = dayjs()
    // console.log(typeof state.store.users.id)
    // console.log(state.store.users.id)
}

//编辑

async function saveFun(datas) {
    state.titleTxt = '修改'
    state.config.loading = false
    let dataNew = XEUtils.clone(datas, true)
    state.formData = dataNew
}

const disabledEndDate = current => {
    if (state.formData.taskSendTime) {
        return current && current <= dayjs(state.formData.taskSendTime).startOf('day')
    }
}

//关闭

function close() {
    state.formRef.clearValidate()
    state.formData = {}
    state.config.visible = false
    state.customerInfo = []
}

//初始化

function openModel(type, datas) {
    // 公共配置
    state.config.width = 650
    state.modelType = type
    state.config.visible = true
    state.config.loading = true
    //新增|编辑|详情
    type === 0 ? createFun() : type === 1 ? saveFun(datas) : viewFun(datas)
}

// 常用

watch(
    () => state.formData.director,
    newArr => {
        if (state.formData.director === '') {
            state.formData.directorNumber === ''
            state.formData.department === ''
        }
    },
    { deep: true, immediate: true }
)

//导出

defineExpose({
    openModel,
})

const { formRef, formData, chooseCustomerRef } = toRefs(state)
</script>
